package com.swt.controller.W_controller;

import com.alibaba.fastjson.JSON;
import com.swt.domain.Admin;
import com.swt.service.impl.W_impl.AdminServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/AdminController")
public class AdminController {
    @Resource
    private AdminServiceImpl adminServiceImpl;

    /**
     * 管理员登录校验
     * */
    @RequestMapping("/login")
    @ResponseBody
    public String login(Admin admin, HttpServletRequest request){
        List<Admin>list=adminServiceImpl.login(admin);
        if(list.size()!=0){
            request.getSession().setAttribute("ADMIN_SESSION_KEY",admin);
            return JSON.toJSONString("true");
        }
        return JSON.toJSONString("false");
    }

    /**
     * 管理员注册校验
     * */
    @RequestMapping("/register")
    @ResponseBody
    public String register(Admin admin){
        List<Admin>list=adminServiceImpl.login(admin);
        if(list.size()!=0){
            return JSON.toJSONString("false");
        }else {
            adminServiceImpl.add(admin);
            return JSON.toJSONString("true") ;
        }

    }

    /**
     * 管理员退出登录
     * */
    @RequestMapping("/exit")
    public String exit(HttpServletRequest req){
        req.getSession().removeAttribute("ADMIN_SESSION_KEY");
        System.out.println("session已清空");
        return "redirect:/background/login.html";
    }

    /**
     * 修改管理员密码
     * */
    @RequestMapping("/editPassword")
    @ResponseBody
    public String editPassword(HttpServletRequest req,String oldpassword,String newpassword){
        Admin admin= (Admin) req.getSession().getAttribute("ADMIN_SESSION_KEY");
        Admin admin1=null;
        List<Admin>list=adminServiceImpl.login(admin);
        for (Admin admin2 : list) {
            admin1=admin2;
        }
        if(list.size()!=0&&admin.getAdminPassword().equals(oldpassword)){
            admin1.setAdminPassword(newpassword);
            adminServiceImpl.editPassword(admin1);
            return JSON.toJSONString("true");
        }
        return JSON.toJSONString("false");
    }

}
